package com.tjbklx1.redis.chap01;

import java.util.HashMap;

import org.junit.Test;

import redis.clients.jedis.Jedis;

/**
 * chap1.3 案例
 * 
 * @author Administrator
 *
 */
public class App02 {

	private static final int ONE_WEEK_IN_SECONDS = 7 * 86400;
	private static final int VOTE_SCORE = 432;
	private static final int ARTICLES_PER_PAGE = 25;

	@Test
	public void process() {

		Jedis conn = new Jedis("localhost");
		conn.select(1);

		String articleId = postArticle(conn, "username", "A title", "http://www.google.com");
		System.out.println("We posted a new article with id: " + articleId);

		System.out.println("===========================");

		conn.close();
	}

	public String postArticle(Jedis conn, String user, String title, String link) {
		String articleId = String.valueOf(conn.incr("article:"));

		String voted = "voted:" + articleId;
		conn.sadd(voted, user);
		conn.expire(voted, ONE_WEEK_IN_SECONDS);

		long now = System.currentTimeMillis() / 1000;
		String article = "article:" + articleId;
		HashMap<String, String> articleData = new HashMap<String, String>();
		articleData.put("title", title);
		articleData.put("link", link);
		articleData.put("user", user);
		articleData.put("now", String.valueOf(now));
		articleData.put("votes", "1");
		conn.hmset(article, articleData);
		conn.zadd("score:", now + VOTE_SCORE, article);
		conn.zadd("time:", now, article);

		return articleId;
	}
}
